#!/usr/bin/env python3
"""
生成测试内容数据
用于测试推荐系统功能
"""

import asyncio
from datetime import datetime, timedelta
from sqlalchemy.orm import Session
import random

from models import get_db, Content, ContentTag, ContentMedia, User, Tag, UserTag

class TestDataGenerator:
    """测试数据生成器"""
    
    def __init__(self):
        self.db = next(get_db())
    
    def generate_test_content(self, count: int = 50):
        """生成测试内容"""
        print(f"开始生成 {count} 条测试内容...")
        
        # 获取所有用户
        users = self.db.query(User).all()
        if not users:
            print("❌ 没有找到用户，请先创建用户")
            return
        
        # 获取所有标签
        tags = self.db.query(Tag).all()
        if not tags:
            print("❌ 没有找到标签，请先初始化标签")
            return
        
        # 测试内容模板
        content_templates = [
            {
                "title": "美食分享：{food}的制作方法",
                "description": "今天分享一道美味的{food}，简单易做，营养丰富。{tips}",
                "tags": ["美食", "烹饪", "家常菜"]
            },
            {
                "title": "旅行攻略：{place}的必去景点",
                "description": "刚刚从{place}回来，整理了一份详细的旅行攻略。{highlights}",
                "tags": ["旅行", "攻略", "景点"]
            },
            {
                "title": "生活小贴士：{tip}",
                "description": "分享一个实用的生活小贴士，{tip}。{details}",
                "tags": ["生活", "小贴士", "实用"]
            },
            {
                "title": "健身心得：{sport}训练分享",
                "description": "坚持{sport}训练已经{time}了，分享一些心得体会。{experience}",
                "tags": ["健身", "运动", "健康"]
            },
            {
                "title": "摄影技巧：{scene}拍摄指南",
                "description": "分享一些{scene}拍摄的技巧和经验。{tips}",
                "tags": ["摄影", "技巧", "艺术"]
            }
        ]
        
        # 内容素材
        foods = ["红烧肉", "宫保鸡丁", "麻婆豆腐", "糖醋排骨", "鱼香肉丝", "回锅肉", "水煮鱼", "酸菜鱼"]
        places = ["杭州", "上海", "北京", "成都", "西安", "厦门", "青岛", "大连"]
        tips = ["如何快速整理房间", "省钱购物技巧", "时间管理方法", "健康饮食搭配", "护肤保养心得"]
        sports = ["跑步", "瑜伽", "游泳", "健身", "骑行", "爬山", "篮球", "羽毛球"]
        scenes = ["风景", "人像", "夜景", "微距", "街拍", "建筑", "美食", "宠物"]
        
        generated_count = 0
        
        for i in range(count):
            try:
                # 随机选择模板和素材
                template = random.choice(content_templates)
                user = random.choice(users)
                
                # 生成内容
                if "美食" in template["title"]:
                    food = random.choice(foods)
                    title = template["title"].format(food=food)
                    description = template["description"].format(
                        food=food,
                        tips="制作时要注意火候控制，这样口感会更好。"
                    )
                elif "旅行" in template["title"]:
                    place = random.choice(places)
                    title = template["title"].format(place=place)
                    description = template["description"].format(
                        place=place,
                        highlights="这里的风景真的很美，值得一去。"
                    )
                elif "生活" in template["title"]:
                    tip = random.choice(tips)
                    title = template["title"].format(tip=tip)
                    description = template["description"].format(
                        tip=tip,
                        details="这个方法真的很实用，推荐给大家。"
                    )
                elif "健身" in template["title"]:
                    sport = random.choice(sports)
                    time = random.choice(["3个月", "半年", "1年", "2年"])
                    title = template["title"].format(sport=sport)
                    description = template["description"].format(
                        sport=sport,
                        time=time,
                        experience="坚持就是胜利，大家一起加油！"
                    )
                elif "摄影" in template["title"]:
                    scene = random.choice(scenes)
                    title = template["title"].format(scene=scene)
                    description = template["description"].format(
                        scene=scene,
                        tips="掌握这些技巧，你也能拍出好照片。"
                    )
                else:
                    title = f"测试内容 {i+1}"
                    description = f"这是第 {i+1} 条测试内容，用于测试推荐系统功能。"
                
                # 创建内容
                content = Content(
                    title=title,
                    description=description,
                    author_id=user.id,
                    status=2,  # 已发布
                    view_count=random.randint(10, 1000),
                    like_count=random.randint(0, 200),
                    comment_count=random.randint(0, 50),
                    share_count=random.randint(0, 30),
                    collect_count=random.randint(0, 100),
                    is_top=random.choice([True, False]),
                    created_at=datetime.utcnow() - timedelta(days=random.randint(0, 30)),
                    published_at=datetime.utcnow() - timedelta(days=random.randint(0, 30))
                )
                
                self.db.add(content)
                self.db.flush()  # 获取ID
                
                # 添加标签
                content_tags = []
                for tag_name in template["tags"]:
                    tag = next((t for t in tags if t.name == tag_name), None)
                    if tag:
                        content_tag = ContentTag(
                            content_id=content.id,
                            tag_id=tag.id
                        )
                        self.db.add(content_tag)
                        content_tags.append(content_tag)
                
                # 随机添加1-3个额外标签
                extra_tags = random.sample([t for t in tags if t.name not in template["tags"]], 
                                         min(random.randint(1, 3), len(tags) - len(template["tags"])))
                for tag in extra_tags:
                    content_tag = ContentTag(
                        content_id=content.id,
                        tag_id=tag.id
                    )
                    self.db.add(content_tag)
                    content_tags.append(content_tag)
                
                # 添加媒体文件
                media_count = random.randint(1, 3)
                for j in range(media_count):
                    media = ContentMedia(
                        content_id=content.id,
                        media_url=f"https://picsum.photos/400/300?random={i*10+j}",
                        media_type="image",
                        sort_order=j + 1,
                        width=400,
                        height=300,
                        file_size=random.randint(50000, 500000)
                    )
                    self.db.add(media)
                
                generated_count += 1
                
                if generated_count % 10 == 0:
                    print(f"已生成 {generated_count} 条内容...")
                
            except Exception as e:
                print(f"生成第 {i+1} 条内容失败: {e}")
                continue
        
        # 提交事务
        self.db.commit()
        print(f"✅ 成功生成 {generated_count} 条测试内容")
        
        return generated_count
    
    def generate_user_tags(self):
        """为现有用户生成兴趣标签"""
        print("为用户生成兴趣标签...")
        
        users = self.db.query(User).all()
        tags = self.db.query(Tag).all()
        
        if not users or not tags:
            print("❌ 没有找到用户或标签")
            return
        
        generated_count = 0
        
        for user in users:
            # 检查用户是否已有标签
            existing_tags = self.db.query(UserTag).filter(UserTag.user_id == user.id).all()
            if existing_tags:
                continue
            
            # 随机选择3-5个标签
            selected_tags = random.sample(tags, random.randint(3, min(5, len(tags))))
            
            for tag in selected_tags:
                user_tag = UserTag(
                    user_id=user.id,
                    tag_id=tag.id
                )
                self.db.add(user_tag)
                generated_count += 1
        
        self.db.commit()
        print(f"✅ 为用户生成了 {generated_count} 个兴趣标签")
        
        return generated_count
    
    def cleanup_test_data(self):
        """清理测试数据"""
        print("清理测试数据...")
        
        try:
            # 删除内容媒体
            self.db.query(ContentMedia).delete()
            
            # 删除内容标签关联
            self.db.query(ContentTag).delete()
            
            # 删除内容
            self.db.query(Content).delete()
            
            # 删除用户标签关联
            self.db.query(UserTag).delete()
            
            self.db.commit()
            print("✅ 测试数据清理完成")
            
        except Exception as e:
            print(f"❌ 清理测试数据失败: {e}")
            self.db.rollback()

def main():
    """主函数"""
    generator = TestDataGenerator()
    
    print("=== 测试数据生成器 ===")
    print("1. 生成测试内容")
    print("2. 生成用户兴趣标签")
    print("3. 清理测试数据")
    print("4. 全部生成")
    
    choice = input("请选择操作 (1-4): ").strip()
    
    if choice == "1":
        count = int(input("请输入要生成的内容数量 (默认50): ") or "50")
        generator.generate_test_content(count)
    elif choice == "2":
        generator.generate_user_tags()
    elif choice == "3":
        generator.cleanup_test_data()
    elif choice == "4":
        generator.generate_user_tags()
        generator.generate_test_content(50)
    else:
        print("无效选择")

if __name__ == "__main__":
    main()
